package com.ticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.entity.*;
import com.ticket.mapper.MatchMapper;
import com.ticket.service.*;
import com.ticket.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MatchServiceImpl extends ServiceImpl<MatchMapper, Match> implements IMatchService {

    @Autowired
    private ITeamService teamService;

    @Autowired
    private IVenueService venueService;

    @Autowired
    private ITicketPriceService ticketPriceService;

    @Autowired
    private IRefereeService refereeService;

    @Autowired
    private IVolunteerService volunteerService;

    @Autowired
    private IPlayerService playerService;

    @Autowired
    private IVenueSectionService venueSectionService;

    @Autowired
    private ISeatAllocationService seatAllocationService;

    @Override
    public Page<MatchListVO> getMatchList(String status, Long teamId, int page, int size) {
        Page<Match> matchPage = new Page<>(page, size);
        LambdaQueryWrapper<Match> queryWrapper = new LambdaQueryWrapper<>();
//根据状态过滤比赛
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(Match::getStatus, status);
        }

        if (teamId != null) {
            queryWrapper.and(wrapper ->
                wrapper.eq(Match::getHomeTeamId, teamId)
                       .or()
                       .eq(Match::getAwayTeamId, teamId)
            );
        }

        queryWrapper.orderByAsc(Match::getMatchTime);

        Page<Match> result = this.page(matchPage, queryWrapper);

        // 转换为VO
        Page<MatchListVO> voPage = new Page<>();
        BeanUtils.copyProperties(result, voPage, "records");

        List<MatchListVO> voList = new ArrayList<>();
        for (Match match : result.getRecords()) {
            MatchListVO vo = new MatchListVO();
            BeanUtils.copyProperties(match, vo);

            // 获取球队名称
            Team homeTeam = teamService.getById(match.getHomeTeamId());
            Team awayTeam = teamService.getById(match.getAwayTeamId());

            if (homeTeam != null) {
                vo.setHomeTeamName(homeTeam.getName());
                vo.setHomeTeamLogo(homeTeam.getLogoUrl());
            }

            if (awayTeam != null) {
                vo.setAwayTeamName(awayTeam.getName());
                vo.setAwayTeamLogo(awayTeam.getLogoUrl());
            }

            // 获取场馆名称
            Venue venue = venueService.getById(match.getVenueId());
            if (venue != null) {
                vo.setVenueName(venue.getName());
            }

            voList.add(vo);
        }

        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public MatchDetailVO getMatchDetail(Long matchId) {
        Match match = this.getById(matchId);
        if (match == null) {
            return null;
        }

        MatchDetailVO vo = new MatchDetailVO();
        BeanUtils.copyProperties(match, vo);

        // 获取主队信息
        Team homeTeam = teamService.getById(match.getHomeTeamId());
        if (homeTeam != null) {
            vo.setHomeTeamName(homeTeam.getName());
            vo.setHomeTeamLogo(homeTeam.getLogoUrl());

            // 获取主队球员
            List<Player> homePlayers = playerService.getPlayersByTeamId(homeTeam.getId());
            if (!homePlayers.isEmpty()) {
                List<PlayerVO> homePlayerVOs = homePlayers.stream().map(player -> {
                    PlayerVO playerVO = new PlayerVO();
                    BeanUtils.copyProperties(player, playerVO);
                    return playerVO;
                }).collect(Collectors.toList());
                vo.setHomePlayers(homePlayerVOs);
            }
        }

        // 获取客队信息
        Team awayTeam = teamService.getById(match.getAwayTeamId());
        if (awayTeam != null) {
            vo.setAwayTeamName(awayTeam.getName());
            vo.setAwayTeamLogo(awayTeam.getLogoUrl());

            // 获取客队球员
            List<Player> awayPlayers = playerService.getPlayersByTeamId(awayTeam.getId());
            if (!awayPlayers.isEmpty()) {
                List<PlayerVO> awayPlayerVOs = awayPlayers.stream().map(player -> {
                    PlayerVO playerVO = new PlayerVO();
                    BeanUtils.copyProperties(player, playerVO);
                    return playerVO;
                }).collect(Collectors.toList());
                vo.setAwayPlayers(awayPlayerVOs);
            }
        }

        // 获取场馆信息
        Venue venue = venueService.getById(match.getVenueId());
        if (venue != null) {
            vo.setVenueName(venue.getName());
            vo.setVenueCity(venue.getCity());
            vo.setVenueAddress(venue.getAddress());
            vo.setVenueImage(venue.getImageUrl());

            // 获取场馆区域信息
            List<VenueSection> sections = venueSectionService.getSectionsByVenueId(venue.getId());
            if (!sections.isEmpty()) {
                List<VenueSectionVO> sectionVOs = sections.stream().map(section -> {
                    VenueSectionVO sectionVO = new VenueSectionVO();
                    BeanUtils.copyProperties(section, sectionVO);

                    // 计算可用座位数
                    Integer availableSeats = seatAllocationService.getNextAvailableSeat(matchId, section.getId());
                    if (availableSeats != null) {
                        sectionVO.setAvailableSeats(section.getCapacity() - availableSeats + 1);
                        sectionVO.setIsSoldOut(false);
                    } else {
                        sectionVO.setAvailableSeats(0);
                        sectionVO.setIsSoldOut(true);
                    }

                    return sectionVO;
                }).collect(Collectors.toList());
                vo.setVenueSections(sectionVOs);
            }
        }

        // 获取裁判信息
        Referee referee = refereeService.getById(match.getRefereeId());
        if (referee != null) {
            vo.setRefereeName(referee.getName());
            vo.setRefereeLevel(referee.getLevel());
            vo.setRefereePhoto(referee.getPhotoUrl());
        }

        // 获取志愿者信息
        List<Volunteer> volunteers = volunteerService.getVolunteersByIds(match.getVolunteerIds());
        if (!volunteers.isEmpty()) {
            List<VolunteerVO> volunteerVOs = volunteers.stream().map(volunteer -> {
                VolunteerVO volunteerVO = new VolunteerVO();
                volunteerVO.setId(volunteer.getId());
                volunteerVO.setName(volunteer.getName());
                return volunteerVO;
            }).collect(Collectors.toList());
            vo.setVolunteers(volunteerVOs);
        }

        // 获取票价信息
        vo.setTicketPrices(ticketPriceService.getTicketPricesByMatchId(matchId));

        return vo;
    }

    @Override
    public List<MatchDetailVO> getRecentMatches(int limit) {
        LambdaQueryWrapper<Match> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Match::getMatchTime, LocalDateTime.now())  // 只查询未来的比赛
                   .orderByAsc(Match::getMatchTime)  // 按时间升序
                   .last("LIMIT " + limit);

        List<Match> matches = this.baseMapper.selectList(queryWrapper);
        List<MatchDetailVO> list = new ArrayList<>();
        // 填充球队和场馆信息
        matches.forEach(match -> {
            list.add(getMatchDetail(match.getId()));
        });

        return list;
    }
}
